$(document).ready(function () {
    $("#step").steps({
        onFinish: function () { alert('Wizard Completed'); }
    });

    tinymce.init({
        selector: "textarea#myText",
        height: 500,
        theme: 'modern',
        plugins: ['link', 'table', 'image', 'media'],
        image_title: true,
        // enable automatic uploads of images represented by blob or data URIs
        automatic_uploads: true,
        // URL of our upload handler (for more details check: https://www.tinymce.com/docs/configure/file-image-upload/#images_upload_url)
        // images_upload_url: 'postAcceptor.php',
        // here we add custom filepicker only to Image dialog
        file_picker_types: 'image',

        file_picker_callback: function (cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function () {
                var file = input.files[0];

                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function () {
                    var img = reader.result.toString();
                    cb(img, { title: file.name });
                }
            };
            input.click();
        },
        images_dataimg_filter: function (img) {
            return img.hasAttribute('internal-blob');
        }
    });

    var tree = [];
    $.ajax({
        url: "http://localhost:8080/GeoModeling/ModelRepositoryServlet",
        type: "GET",
        async: false,
        success: function (result) {
            result = result.replace(new RegExp("children", "gm"), "nodes");
            result = result.replace(new RegExp("nameEn", "gm"), "text");
            tree = JSON.parse(result);
            createTree();
        }
    });

    function createTree() {
        $('#tree').treeview({
            data: tree
        })
    }

    $('#tree').on('nodeSelected', function (event, data) {
        console.log(event);
        console.log(data);
        if (data.nodes === undefined) {
            $("#parentNode").val(data.text);
            $("#parentNode").attr("pid", data.id);
        }
    });

    $('#tagInput').tagEditor({
        forceLowercase: false
    });

    $("#imgChange").click(function(){
        $("#imgFile").click();
    });
    $("#imgFile").change(function(){
        //获取input file的files文件数组;
        //$('#filed')获取的是jQuery对象，.get(0)转为原生对象;
        //这边默认只能选一个，但是存放形式仍然是数组，所以取第一个元素使用[0];
        var file = $('#imgFile').get(0).files[0];
        //创建用来读取此文件的对象
        var reader = new FileReader();
        //使用该对象读取file文件
        reader.readAsDataURL(file);
        //读取文件成功后执行的方法函数
        reader.onload=function(e){
            //读取成功后返回的一个参数e，整个的一个进度事件
            //选择所要显示图片的img，要赋值给img的src就是e中target下result里面
            //的base64编码格式的地址
             $('#imgShow').get(0).src = e.target.result;
             $('#imgShow').show();
        }
    });

    var modelItemObj = {};
    $(".next").click(function(){        
        modelItemObj.ParentId = [$("#parentNode").attr("pid")];
        modelItemObj.Name = $("#nameInput").val();
        modelItemObj.Tags = $("#tagInput").val().split(",");
        modelItemObj.Description = $("#descInput").val();
        modelItemObj.image = $('#imgShow').get(0).src;
        modelItemObj.showOnIndex = $("input[name='item']:checked").val();
    });

    $(".finish").click(function(){
        var detail = tinyMCE.activeEditor.getContent();
        modelItemObj.Detail = detail;
        if($("#parentNode").attr("pid")===undefined){
            alert("Please select parent node");
            return;
        }
        if( $("#nameInput").val()===""){
            alert("Please enter model item name");
            return;
        }
        console.log(modelItemObj);
        $.ajax({
            url: "http://localhost:8080/GeoModeling/AddModelItemServlet",
            type:"POST",
            async:true,
            data:{modelItem:JSON.stringify(modelItemObj)},
            dataType:"json",
            success:function(result){
                if(result.result==="success"){
                    alert("Create Success");
                    window.location.href = "modelItems.html";
                }
            }
        })
    });
});